<template>
    <div class="padding">
        <el-button type="primary" @click="customDialog?.open" style="margin: 12px 0;">添加权限</el-button>
        <el-table :data="permissionsData" style="width: 100%">
            <el-table-column prop="id" label="编号" />
            <el-table-column prop="path" label="可访问路径" />
            <el-table-column prop="permissions" label="权限级别" />
            <el-table-column prop="actions" label="行为" />
            <el-table-column label="操作">
                <template #default="scoped">
                    <el-button type="danger" @click="handledelete(scoped.row.id)">删除</el-button>
                    <el-button type="primary" @click="openUpdate(scoped.row)">修改</el-button>
                </template>
            </el-table-column>
        </el-table>
        <CustomDialog ref="customDialog">
            <el-button type="danger" @click="customDialog?.close">取消</el-button>
            <el-button type="primary" @click="sure">确定</el-button>
        </CustomDialog>
        <CustomDialog ref="customUpdateDialog">
            <el-button type="danger" @click="customUpdateDialog?.close">取消</el-button>
            <el-button type="primary" @click="handleUpdate">确定</el-button>
        </CustomDialog>
    </div>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ref } from 'vue';
import CustomDialog, { Expose } from "./dialog.vue"
import { ElMessage } from "element-plus"

const permissionsData = ref([])
const customDialog = ref<Expose>()
const customUpdateDialog = ref<Expose>()

const getPer = () => {
    axios.get("/api/getPers").then(d => {
        permissionsData.value = d.data
    })
}

getPer()

const sure = () => {
    const val = customDialog.value?.getFormData()
    axios.post("/api/addPer", val).then((d) => {
        ElMessage.success({
            message: d.data.message
        })
        customDialog.value?.close()
    })
}

const handledelete = (id: number) => {
    axios.post("/api/deletePer", { id }).then(d => {
        ElMessage.success({
            message: d.data.message
        })
        getPer()
    })
}

const handleUpdate = (row: FormData) => {
    customDialog.value?.updateFormData(row)
    const changedData = customUpdateDialog.value?.getFormData()

    axios.post("/api/updatePer", changedData).then(d => {
        ElMessage.success({
            message: d.data.message
        })
        customUpdateDialog.value?.close()
        getPer()
    })
}

const openUpdate = (row: any) => {
    customUpdateDialog.value?.updateFormData(row)
    customUpdateDialog.value?.open()
}

</script>

<style scoped></style>